/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mangaviewer.json;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonWriter;
import com.mangaviewer.model.Manga;
import com.mangaviewer.util.SearchConstants;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author dorian
 */
public class IOMangaJsonFile {
  
  public static List<Manga> parse(String string) {
    Logger.getLogger(IOMangaJsonFile.class.getName()).log(Level.INFO, "parsing string...");
    JsonParser jp = new JsonParser();
    JsonElement jsonContent = jp.parse(string);
    JsonArray jsonManga = jsonContent.getAsJsonObject().getAsJsonArray("manga");
    
    Gson gson = new Gson();
    Type mangaType = new TypeToken<List<Manga>>() {
    }.getType();
    return gson.fromJson(jsonManga, mangaType);
  }
  
  public static List<Manga> parse(FileReader fr) {
    Logger.getLogger(IOMangaJsonFile.class.getName()).log(Level.INFO, "parsing file...");
    JsonParser jp = new JsonParser();
    JsonElement jsonContent = jp.parse(fr);
    JsonArray jsonManga = jsonContent.getAsJsonObject().getAsJsonArray("manga");
    
    Gson gson = new Gson();
    Type mangaType = new TypeToken<List<Manga>>() {
    }.getType();
    return gson.fromJson(jsonManga, mangaType);
  }

  public static List<Manga> read() throws FileNotFoundException {
    Logger.getLogger(IOMangaJsonFile.class.getName()).log(Level.INFO, "reading manga.json file...");

    FileReader fr = new FileReader(SearchConstants.MANGA_JSON_FILE);

    return parse(fr);
  }
  
  public static void write(List<Manga> manga) throws FileNotFoundException, IOException {
    Logger.getLogger(IOMangaJsonFile.class.getName()).log(Level.INFO, "writing to manga.json file...");
    
    Gson gson = new Gson();
    Type mangaType = new TypeToken<List<Manga>>() {
    }.getType();
    
    String jsonString = gson.toJson(manga, mangaType);
    jsonString = "{\"manga\":" + jsonString + "}";
    
    FileWriter fw = new FileWriter(SearchConstants.MANGA_JSON_FILE);
    fw.write(jsonString);
    fw.close();
  }
}
